# -*- coding: utf-8 -*-
"""
错误分析模块
负责分析日志文件中的错误信息，识别11种错误类型
"""

import re
from typing import List, Dict, Tuple
from dataclasses import dataclass


@dataclass
class ErrorInfo:
    """错误信息数据类"""
    error_type: str
    line_number: int
    error_content: str
    keyword: str


class ErrorAnalyzer:
    """错误分析器"""
    
    def __init__(self):
        """初始化错误分析器，定义错误类型和关键字"""
        self.error_patterns = {
            "应用崩溃（Crash）": re.compile(r"(AndroidRuntime: FATAL EXCEPTION|// CRASH:|java\.lang\.NullPointerException|Monkey aborted due to error)"),
            "应用无响应（ANR）": re.compile(r"(ANR in|Application Not Responding|main thread.*blocked|ANR detected)"),
            "强制关闭（Force Close）": re.compile(r"(Force finishing activity|Force Close|Application terminated|OutOfMemoryError.*Force)"),
            "进程意外退出（Process Death）": re.compile(r"(Process .* \(pid \d+\) has died|Process killed|Low memory killer|ActivityManager.*killing)"),
            "内存不足（OOM）": re.compile(r"(OutOfMemoryError|Out of memory|OOM|Failed to allocate.*byte allocation)"),
        }
    
    def analyze_log(self, log_lines: List[str]) -> Tuple[List[ErrorInfo], bool]:
        """
        分析日志文件，提取错误信息并检测Monkey测试是否成功完成
        
        Args:
            log_lines (List[str]): 日志文件行列表
            
        Returns:
            Tuple[List[ErrorInfo], bool]: (发现的错误信息列表, 是否成功完成)
        """
        errors = []
        monkey_finished = False
        
        # 检测Monkey finished
        for i, line in enumerate(log_lines, 1):
            if "Monkey finished" in line:
                monkey_finished = True
                break
        
        # 检测错误
        for i, line in enumerate(log_lines, 1):
            for error_type, pattern in self.error_patterns.items():
                if pattern.search(line):
                    error_info = ErrorInfo(
                        error_type=error_type,
                        line_number=i,
                        error_content=line.strip(),
                        keyword=pattern.pattern
                    )
                    errors.append(error_info)
        
        return errors, monkey_finished
    
    def get_error_summary(self, errors: List[ErrorInfo]) -> Dict[str, int]:
        """
        获取错误统计摘要
        
        Args:
            errors (List[ErrorInfo]): 错误信息列表
            
        Returns:
            Dict[str, int]: 错误类型统计
        """
        summary = {}
        for error in errors:
            if error.error_type in summary:
                summary[error.error_type] += 1
            else:
                summary[error.error_type] = 1
        
        return summary    
    def filter_errors_by_type(self, errors: List[ErrorInfo], error_type: str) -> List[ErrorInfo]:
        """
        按错误类型过滤错误
        
        Args:
            errors (List[ErrorInfo]): 错误信息列表
            error_type (str): 要过滤的错误类型
            
        Returns:
            List[ErrorInfo]: 过滤后的错误列表
        """
        return [error for error in errors if error.error_type == error_type]
    
    def analyze_errors(self, log_content):
        """
        分析日志内容，提取错误信息。
        """
        print("--- Analyzing Errors ---") # Debug print
        errors = {}
        for error_type, pattern in self.error_patterns.items():
            print(f"Checking for: {error_type} with pattern: {pattern}") # Debug print
            matches = re.findall(pattern, log_content)
            if matches:
                print(f"Found {len(matches)} matches for {error_type}") # Debug print
                if error_type not in errors:
                    errors[error_type] = []
                for match in matches:
                    errors[error_type].append(match)
            else:
                print(f"No matches for {error_type}") # Debug print
        print("--- Analysis Complete ---") # Debug print
        return errors
